package com.snail.starter.db.fill;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.snail.starter.commons.threadlocal.UserContext;
import com.snail.starter.commons.threadlocal.UserContextUtils;
import org.apache.ibatis.reflection.MetaObject;

/**
 * @author: snail framework
 * @Date: 2023/2/23 下午5:05
 * @Version: 1.0.0
 */
public class CustomMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        UserContext userContext = UserContextUtils.get();
        if (metaObject.hasSetter("created") && null == metaObject.getValue("created")) {
            this.strictInsertFill(metaObject, "created", System::currentTimeMillis, Long.class);
        }
        if (metaObject.hasSetter("createBy") && null == metaObject.getValue("createBy")) {
            this.strictInsertFill(metaObject, "createBy", userContext::getUserId, Long.class);
        }
        if (metaObject.hasSetter("modified") && null == metaObject.getValue("modified")) {
            this.strictInsertFill(metaObject, "modified", System::currentTimeMillis, Long.class);
        }
        if (metaObject.hasSetter("modifyBy") && null == metaObject.getValue("modifyBy")) {
            this.strictInsertFill(metaObject, "modifyBy", userContext::getUserId, Long.class);
        }
        if (metaObject.hasSetter("deleted") && null == metaObject.getValue("deleted")) {
            this.strictInsertFill(metaObject, "deleted", () -> 0L, Long.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        UserContext userContext = UserContextUtils.get();
        if (metaObject.hasSetter("modified") && null == metaObject.getValue("modified")) {
            this.strictInsertFill(metaObject, "modified", System::currentTimeMillis, Long.class);
        }
        if (metaObject.hasSetter("modifyBy") && null == metaObject.getValue("modifyBy")) {
            this.strictInsertFill(metaObject, "modifyBy", userContext::getUserId, Long.class);
        }
    }
}
